package com.wxy.ej.flow.modules.taskflow.service.ds;

import com.wxy.ej.flow.modules.taskflow.bean.TaskFlowDs;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MysqlUtils {

    private static Connection getConnection(TaskFlowDs taskFlowDs) throws SQLException {
        String url = taskFlowDs.getUrl();
        String username = taskFlowDs.getUsername();
        String password = taskFlowDs.getPassword();
        String extend = taskFlowDs.getExtend();
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        conn= DriverManager.getConnection(url,username,password);
        return conn;
    }


    /**
     * 功能：查询表，以List形式返回记录集
     * @param taskFlowDs
     * @param sql
     * @param paraList
     * @return 记录集
     * @throws SQLException
     * @author wuxiaoyong
     */
    public static List<Map<String, Object>> queryList(TaskFlowDs taskFlowDs, String sql, List paraList) throws SQLException {
        Connection conn = getConnection(taskFlowDs);
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        List<Map<String, Object>> list = new ArrayList();
        try{
            pstmt = conn.prepareStatement(sql);
            int i=1;
            if(paraList!=null){
                for(Object o:paraList){
                    pstmt.setObject(i++, o);
                }
            }

            rs = pstmt.executeQuery();
            while(rs.next()){
                HashMap map = new HashMap();
                ResultSetMetaData rsmd = rs.getMetaData();
                int count = rsmd.getColumnCount();
                for(int j=1; j<=count; j++){
                    String columnName = rsmd.getColumnName(j);
                    map.put(columnName, rs.getObject(columnName));
                }
                list.add(map);
            }
        }finally{
            if(rs!=null)rs.close();
            if(pstmt!=null)pstmt.close();
            if(conn!=null)conn.close();
        }

        return list;
    }
}
